package ws

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
)

func NewVisitorWs(c *gin.Context) {
	roomId := c.Query("room_id")
	name := c.Query("name")
	id := c.Query("id")
	avator := c.Query("avator")

	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	visitor := &Visitor{
		Name:   name,
		Id:     id,
		Avator: avator,
		Conn:   conn,
	}
	members, _ := Room.GetMembers(roomId)
	members = append(members, visitor)
	Room.SetMembers(roomId, members)

	log.Println("ws connect...")

	for {
		//接受消息
		_, receive, err := conn.ReadMessage()
		if err != nil {
			log.Println(err)
			return
		}
		log.Println("ws receive : ", string(receive))
		conn.WriteMessage(websocket.TextMessage, receive)
	}
}
